﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Reporting.WinForms;
using SWF = System.Windows.Forms;
using System.Configuration;
using SQLServerHealthCheck.Model;
using System.Collections.ObjectModel;
using SQLServerHealthCheck.SQLServer;
using AG.Utilities;
using SQLServerHealthCheck.PL.WPF.DataSet.DataSetDatabasesAndFilesTableAdapters;
using SQLServerHealthCheck.PL.WPF.DataSet;
using SQLServerHealthCheck.PL.DataSetServerAndServicesTableAdapters;
using SQLServerHealthCheck.PL;
using SQLServerHealthCheck.PL.DataSetDatabaseFragmentationTableAdapters;
using SQLServerHealthCheck.PL.DataSetSQLAgentJobResultsTableAdapters;
using SQLServerOptimizer.PL.WPF.Datasets.DataSetNonClusteredUnusedIndexesTableAdapters;
using SQLServerOptimizer.PL.WPF.Datasets;

namespace SQLServerOptimizer.PL.WPF
{
    /// <summary>
    /// Interaction logic for OverviewReportsControl.xaml
    /// </summary>
    public partial class OverviewReportsControl : UserControl
    {
        HealthCheckDataContext dc;
        List<Service> SQLServerInstances;

        public OverviewReportsControl()
        {
            InitializeComponent();
        }

        public void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
                if (MainWindow.IsDatabaseCreated() )
                {
                    string conn = System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase");
                    CheckInstanceStatusWorker checkinstanceStatusworker = new CheckInstanceStatusWorker(this, conn);

                    checkinstanceStatusworker.AccessiblityResult += new InstanceStatusResult(checkinstanceStatusworker_AccessiblityResult);
                    checkinstanceStatusworker.Start();
                }
            }
            catch (Exception sql)
            {
                Logger.Error(sql);


            }
        }

        private void checkinstanceStatusworker_AccessiblityResult(bool accessible)
        {
            try
            {

                if (accessible)
                {
                    dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));

                    var qry = from i in dc.Services
                              where i.ServiceTypeID == 1
                              select i;
                    SQLServerInstances = qry.ToList<Service>();
                    Server dummy = new Server { Name = "All" };
                    Service dummyService = new Service { ServiceID = -1, Server = dummy, Name = "" };
                    
                    SQLServerInstances.Insert(0, dummyService);
                    var main = App.Current.MainWindow as MainWindow;
                    int ind = main.cboInstances.SelectedIndex;
                    main.cboInstances.ItemsSource = SQLServerInstances;
                    main.cboInstances.DisplayMemberPath = "InstanceName";
                   main.cboInstances.SelectedValuePath = "ServiceID";
                   main.cboInstances.SelectedIndex = ind;

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

     

        public void ShowServersAndServices()
        {
            try
            {
                ReportViewer viewer = (ReportViewer)wfh_report.Child;

                ServerAndServicesTableAdapter adapter = new ServerAndServicesTableAdapter();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];

                DataSetServerAndServices dataset = new DataSetServerAndServices();

                adapter.Fill(dataset.ServerAndServices);


                SWF.BindingSource bindingSource = new SWF.BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "ServerAndServices";


                ReportDataSource reportDataSource = new ReportDataSource();

                //reportDataSource.Name = "IssuesReportDataset";
                reportDataSource.Name = "ServerAndServices";
                reportDataSource.Value = bindingSource;

                viewer.LocalReport.DataSources.Clear();
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = SWF.BorderStyle.None;


                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\ServerAndServices.rdlc";
                viewer.RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }
        public void ShowUnusedNonClusteredIndexes()
        {
            try
            {
                ReportViewer viewer = (ReportViewer)wfh_report.Child;
                var main = App.Current.MainWindow as MainWindow;
                UnusedNonClusteredIndexesTableAdapter adapter = new UnusedNonClusteredIndexesTableAdapter();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];

                DataSetNonClusteredUnusedIndexes dataset = new DataSetNonClusteredUnusedIndexes();


                int ServiceID;

                if (main.cboInstances.SelectedIndex != -1)
                {
                    ServiceID = (main.cboInstances.SelectedItem as Service).ServiceID;
                }
                else
                {
                    ServiceID = -1;
                }


                int databaseID;

                if (main.cboDatabases.SelectedIndex != -1)
                {
                    databaseID = (main.cboDatabases.SelectedItem as Database).DatabaseID;
                }
                else
                {
                    databaseID = -1;
                }


                adapter.Fill(dataset.UnusedNonClusteredIndexesPerDatabase,ServiceID, databaseID);


                SWF.BindingSource bindingSource = new SWF.BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "UnusedNonClusteredIndexesPerDatabase";


                ReportDataSource reportDataSource = new ReportDataSource();

                //reportDataSource.Name = "IssuesReportDataset";
                reportDataSource.Name = "UnusedNonClusteredIndexes";
                reportDataSource.Value = bindingSource;

                viewer.LocalReport.DataSources.Clear();
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = SWF.BorderStyle.None;


                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\NonClusteredUnusedIndexes.rdlc";
                viewer.RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }
        public void ShowDatabases()
        {
            try
            {
                ReportViewer viewer = (ReportViewer)wfh_report.Child;
                var main = App.Current.MainWindow as MainWindow;
                TableAdapterDatabasesAndFiles adapter = new TableAdapterDatabasesAndFiles();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];

                DataSetDatabasesAndFiles dataset = new DataSetDatabasesAndFiles();

                int ServiceID;

                int databaseID;

                if (main.cboDatabases.SelectedIndex != -1)
                {
                    databaseID = (main.cboDatabases.SelectedItem as Database).DatabaseID;
                }
                else
                {
                    databaseID = -1;
                }


                if (main.cboInstances.SelectedIndex != -1)
                {
                    ServiceID = (main.cboInstances.SelectedItem as Service).ServiceID;
                }
                else
                {
                    ServiceID = -1;
                }

                adapter.Fill(dataset.DatabasesAndFiles, ServiceID, databaseID);

                SWF.BindingSource bindingSource = new SWF.BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "DatabasesAndFiles";


                ReportDataSource reportDataSource = new ReportDataSource();

                reportDataSource.Name = "DatabasesAndFiles";
                reportDataSource.Value = bindingSource;

                viewer.LocalReport.DataSources.Clear();
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = SWF.BorderStyle.None;

                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\DatabasesAndFiles.rdlc";
                viewer.LocalReport.Refresh();
                viewer.RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        public void ShowIndexes()
        {
            var mainwindow = Application.Current.Windows.Cast<Window>().First();
            try
            {
                
                ReportViewer viewer = (ReportViewer)wfh_report.Child;
                var main = App.Current.MainWindow as MainWindow;
                TableAdapterDatabaseFragmentation adapter = new TableAdapterDatabaseFragmentation();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];

                DataSetDatabaseFragmentation dataset = new DataSetDatabaseFragmentation();


                int ServiceID;

                if (main.cboInstances.SelectedIndex != -1)
                {
                    ServiceID = (main.cboInstances.SelectedItem as Service).ServiceID;
                }
                else
                {
                    ServiceID = -1;
                }


                int databaseID;

                if (main.cboDatabases.SelectedIndex != -1)
                {
                    databaseID = (main.cboDatabases.SelectedItem as Database).DatabaseID;
                }
                else
                {
                    databaseID = -1;
                }



                adapter.Fill(dataset.Top10PercentIndexesPerDatabase, ServiceID, databaseID);


                SWF.BindingSource bindingSource = new SWF.BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "Top10PercentIndexesPerDatabase";


                ReportDataSource reportDataSource = new ReportDataSource();

                reportDataSource.Name = "DatabaseFragmentation";
                reportDataSource.Value = bindingSource;

                viewer.LocalReport.DataSources.Clear();
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = SWF.BorderStyle.None;


                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\DatabaseFragmentation.rdlc";
                viewer.RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }


        public void ShowSQLAgentJobs()
        {

            try
            {
                ReportViewer viewer = (ReportViewer)wfh_report.Child;
                var main = App.Current.MainWindow as MainWindow;
                SQLAgentJobDetailsTableAdapter adapter = new SQLAgentJobDetailsTableAdapter();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];


                DataSetSQLAgentJobResults dataset = new DataSetSQLAgentJobResults();


                int ServiceID;

                if (main.cboInstances.SelectedIndex != -1)
                {
                    ServiceID = (main.cboInstances.SelectedItem as Service).ServiceID;
                }
                else
                {
                    ServiceID = -1;
                }



                adapter.Fill(dataset.DataTableSQLAgentJobDetails, ServiceID);


                SWF.BindingSource bindingSource = new SWF.BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "DataTableSQLAgentJobDetails";


                ReportDataSource reportDataSource = new ReportDataSource();

                reportDataSource.Name = "SQLAgentJobDetails";
                reportDataSource.Value = bindingSource;

                viewer.LocalReport.DataSources.Clear();
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = SWF.BorderStyle.None;


                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\SQLAgentJobReports.rdlc";
                viewer.RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }



    }
}
